package com.xb.loan.encryptor.crypt.impl;


import com.xb.loan.encryptor.cache.RsaKeyCacheManager;
import com.xb.loan.encryptor.crypt.Encryptor;
import com.xb.loan.encryptor.util.RSAUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PartnerEncryptor implements Encryptor {
	
	private static Log log = LogFactory.getLog(PartnerEncryptor.class);
	
	@Override
	// 使用系统生成的合作商私钥签名
	public String encrypt(String id, String key, String msg) {
		
		byte[] priKeyData = RsaKeyCacheManager.getPartnerKeyCache().getPriKey(id);
		
		if(priKeyData == null){
			
			log.info("PartnerEncryptor.encrypt not get partner " + id + " genPrivateKey.");
			return null;
		}
		
		String sign = null;
		
		try {
			
			sign = RSAUtils.sign(msg.getBytes("utf-8"), priKeyData);
			
		} catch (Exception e) {
			
			log.error("PartnerEncryptor.encrypt have exception,partnerid:" + id,e);
		}
		
		return sign;
	}

	@Override
	// 使用合作商的公钥验证签名
	public boolean encryptValidate(String id, String key, String msg,
                                   String encryptResult) {
		
		byte[] pubKeyData = RsaKeyCacheManager.getPartnerKeyCache().getPubKey(id);
		
		if(pubKeyData == null){
			
			log.info("PartnerEncryptor.encrypt not get partner " + id + " public key.");
			return false;
		}
		
		boolean verify = false;
		
		try {
			
			verify = RSAUtils.verify(msg.getBytes("utf-8"), pubKeyData, encryptResult);
			
		} catch (Exception e) {
			
			log.error("PartnerEncryptor.encryptValidate have exception,partnerid:" + id,e);
		}
		
		return verify;
	}

}
